package fu.k4c.vTeam.Login;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
import fu.k4c.vTeam.R;
import fu.k4c.vTeam.Main.MainActivity;
import fu.k4c.vTeam.Object.Account;
import fu.k4c.vTeam.Object.Information;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class EditInfoActivity extends Activity {
	// Bundle data = getIntent().getExtras();
	String email;
	String sex;
	String role;
	String[] checkFullName = { "Admin", "admin", "Hồ Chí Minh", "Smod",
			"Seniormod", "Mod", "Bố admin", "Bác Hồ" };

	Button btn_birthday;
	static final int DIALOG_DATE_ID = 0;
	private RadioGroup radioSexGroup;
	private RadioButton radioSexButton;
	Calendar birthday = Calendar.getInstance();
	DatePickerDialog.OnDateSetListener bd = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			birthday.set(Calendar.YEAR, year);
			birthday.set(Calendar.MONTH, monthOfYear);
			birthday.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			String date = dayOfMonth + "/" + (monthOfYear + 1) + "/" + year;
			btn_birthday.setText(date);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.information_activity);
		overridePendingTransition(android.R.anim.fade_in,
				android.R.anim.fade_out);
		Bundle data = getIntent().getExtras();
		email = data.getString("email");
		role = data.getString("RoleUser");
		TextView tv_email = (TextView) findViewById(R.id.tv_infor_email2);
		tv_email.setText(email);
		btn_birthday = (Button) findViewById(R.id.btn_infor_birthday);
		final EditText et_address = (EditText) findViewById(R.id.et_infor_address);
		final EditText et_phone = (EditText) findViewById(R.id.et_infor_phone);
		final EditText et_name = (EditText) findViewById(R.id.et_infor_name);

		try {
			// Toast.makeText(getApplicationContext(),
			// data.getString("Birthday"), Toast.LENGTH_LONG).show();
			if (data.getString("Birthday") != null) {
				SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
				Date convertedDate1 = new Date();
				convertedDate1 = dateFormat.parse(data.getString("Birthday"));
				birthday.setTime(convertedDate1);
				String date1 = getDay(birthday.get(Calendar.DAY_OF_MONTH))
						+ "/" + (birthday.get(Calendar.MONTH) + 1) + "/"
						+ birthday.get(Calendar.YEAR);
				btn_birthday.setText(date1);
			}

		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			et_address.setText(data.getString("Address"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			et_phone.setText(data.getString("Phone"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		try {
			et_name.setText(data.getString("FullName"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		String sex1 = data.getString("Sex");
		String sex2 = "Female";
		radioSexGroup = (RadioGroup) findViewById(R.id.rdg_infor_sex);
		RadioButton rdbtn_male = (RadioButton) findViewById(R.id.rd_infor_male);
		RadioButton rdbtn_female = (RadioButton) findViewById(R.id.rd_infor_female);
		// Toast.makeText(getApplicationContext(), data.getString("Sex") +
		// " == " + sex2, Toast.LENGTH_LONG).show();
		if (sex1.trim().equalsIgnoreCase(sex2)) {
			rdbtn_female.setChecked(true);
		} else {
			rdbtn_male.setChecked(true);
		}

		Button btn_change_pass = (Button) findViewById(R.id.btn_infor_changepass);
		btn_change_pass.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent(EditInfoActivity.this,
						ChangePasswordActivity.class);
				// i.putExtra("status", acc.getStatus());
				i.putExtra("email", email);
				startActivity(i);
			}
		});
		Button btn_cancel = (Button) findViewById(R.id.btn_infor_back);
		btn_cancel.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		btn_birthday.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				new DatePickerDialog(EditInfoActivity.this, bd, birthday
						.get(Calendar.YEAR), birthday.get(Calendar.MONTH),
						birthday.get(Calendar.DAY_OF_MONTH)).show();
			}
		});
		Button btn_submit = (Button) findViewById(R.id.btn_infor_submit);
		btn_submit.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				if (et_name.getText().toString().trim().equals("")
						|| et_name.getText().toString() == null
						|| et_phone.getText().toString().trim().equals("")
						|| et_phone.getText().toString() == null
						|| et_address.getText().toString().trim().equals("")
						|| et_address.getText().toString() == null) {
					Toast.makeText(getApplicationContext(),
							"Điền vào chỗ trống", Toast.LENGTH_LONG).show();
				} else {
					boolean isCheck = false;
					for (int i = 0; i < checkFullName.length; i++) {
						if (et_name.getText().toString().toLowerCase()
								.indexOf(checkFullName[i]) >= 0 && role.equals("Supporter")) {
							isCheck = true;
						}
					}
					if (isCheck == true) {
						Toast.makeText(getApplicationContext(),
								"Tên hiển thị sai quy định", Toast.LENGTH_LONG)
								.show();
					} else {
						try {
							SchemeRegistry registry = new SchemeRegistry();
							registry.register(new Scheme("http",
									PlainSocketFactory.getSocketFactory(), 80));
							HttpParams httpParams = new BasicHttpParams();
							ThreadSafeClientConnManager connMgr = new ThreadSafeClientConnManager(
									httpParams, registry);
							HttpClient client = new DefaultHttpClient(connMgr,
									httpParams);
							HttpPost post = new HttpPost(
									getString(R.string.connectionString)
											+ "vLocationService/editprofile");
							post.setHeader("Accept", "application/json");
							post.setHeader("Content-type", "application/json");
							HashMap<String, Object> postParameters = new HashMap<String, Object>();
							int selectedId = radioSexGroup
									.getCheckedRadioButtonId();
							radioSexButton = (RadioButton) findViewById(selectedId);
							if (radioSexButton.getText().toString()
									.equals("Nam")) {
								sex = "Male";
							} else {
								sex = "Female";
							}
							Information user = new Information(email, sex,
									et_name.getText().toString(), et_phone
											.getText().toString(), btn_birthday
											.getText().toString(), et_address
											.getText().toString(), role);

							postParameters.put("UserName", user.getUsername());
							postParameters.put("FullName", user.getFullName());
							postParameters.put("Birthday", user.getBirthday());
							postParameters.put("Phone", user.getPhone());
							postParameters.put("Sex", user.getSex());
							postParameters.put("RoleUser", "");
							postParameters.put("Address", user.getAddress());
							Gson gson = new Gson();
							String jsonParameters = gson.toJson(postParameters);
							post.setEntity(new StringEntity(jsonParameters,
									"UTF-8"));
							HttpResponse response = client.execute(post);

							HttpEntity entity = response.getEntity();
							String jsonresult = EntityUtils.toString(entity);

							Account acc = gson.fromJson(jsonresult,
									Account.class);
							if (acc.getStatus().equals("False")) {
								Toast.makeText(getApplicationContext(),
										"Không thể cập nhật thông tin",
										Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(getApplicationContext(),
										"Cập nhật thông tin thành công!",
										Toast.LENGTH_LONG).show();
								Intent i = new Intent(EditInfoActivity.this,
										MainActivity.class);
								i.putExtra("status", acc.getStatus());
								i.putExtra("email", user.getUsername());
								i.putExtra("fullName", et_name.getText().toString());
								startActivity(i);
							}

						} catch (Exception e) {
							// TODO: handle exception
							Toast.makeText(
									getApplicationContext(),
									"Bạn vui lòng kiểm tra lại kết nối Internet",
									Toast.LENGTH_SHORT).show();
						}
					}
				}

			}
		});
	}

	public String getDay(int day) {
		if (day < 10) {
			return "0" + day;
		}
		return "" + day;
	}

}
